//
//  StockCandleChartView.m
//  K线图自治
//
//  Created by LK-IOS on 2017/12/13.
//  Copyright © 2017年 LK-IOS. All rights reserved.
//

#import "StockCandleChartView.h"
#import "UIColor+StockColorEntension.h"
#import "KVOController.h"
#import "UIView+StockViewExtension.h"
#import "StockKLinePositionModel.h"
#import "StockCalculationTool.h"
#import "StockLinePointModel.h"
#import "StockKLinePositionModel.h"
#import "UIBezierPath+StockDraw.h"

#define MINDISPLAYCOUNT 5

static inline bool isEqualZero(float value)
{
    return fabsf(value) <= 0.00001f;//最小值
}
@interface StockCandleChartView()<UIScrollViewDelegate,UIGestureRecognizerDelegate>

/**
 滚动scrollerView
 */
@property (nonatomic,strong) UIScrollView *superScrollView;
/**
 监听scrollerView的滚动
 */
@property (nonatomic,strong) FBKVOController *KVOController;

/**
 K线图层
 */
@property (nonatomic,strong) CAShapeLayer *lineChartLayer;
//MA5
@property (nonatomic,strong) CAShapeLayer *ma5LineLayer;
//MA10
@property (nonatomic,strong) CAShapeLayer *ma10LineLayer;
//MA25
@property (nonatomic,strong) CAShapeLayer *ma25LineLayer;
/**
 时间图层
 */
@property (nonatomic,strong) CAShapeLayer *timeLayer;

/**
 保存MA线数值的数组
 */
@property (nonatomic ,strong) NSMutableArray *maLines;
/**
 ma线没一点的位置数组
 */
@property (nonatomic,strong) NSMutableArray *maPostionArray;

/**
 时间图层高度
 */
@property (nonatomic,assign) CGFloat timeLayerHeight;




@end

@implementation StockCandleChartView

#pragma mark setter
- (NSMutableArray*)currentDisplayArray
{
    if (!_currentDisplayArray)
    {
        _currentDisplayArray = [NSMutableArray array];
    }
    return _currentDisplayArray;
}

- (NSMutableArray*)currentPostionArray
{
    if (!_currentPostionArray)
    {
        _currentPostionArray = [NSMutableArray array];
    }
    return _currentPostionArray;
}

-(NSMutableArray *)maLines
{
    if (_maLines == nil) {
        _maLines = [NSMutableArray array];
    }
    return _maLines;
}

- (NSMutableArray*)maPostionArray
{
    if (!_maPostionArray)
    {
        _maPostionArray = [NSMutableArray array];
    }
    return _maPostionArray;
}


/**
 添加到父控件上时，添加监听，当scrollerView滚动的时候，绘制视图
 */
-(void)didMoveToSuperview
{
    [super didMoveToSuperview];
    _superScrollView = (UIScrollView*)self.superview;
    _superScrollView.delegate = self;
    
    UIPanGestureRecognizer *panGestureRecognizer = _superScrollView.panGestureRecognizer;
    [panGestureRecognizer addTarget:self action:@selector(panGestureRecognizer:)];
    [self addListener];
}

- (void)addListener
{
    FBKVOController *KVOController = [FBKVOController controllerWithObserver:self];
    self.KVOController = KVOController;
    __weak typeof(self) this = self;
    [self.KVOController observe:_superScrollView keyPath:@"contentOffset" options:NSKeyValueObservingOptionNew block:^(id  _Nullable observer, id  _Nonnull object, NSDictionary<NSString *,id> * _Nonnull change) {
        if (self.kvoEnable)
        {
            this.contentOffset = this.superScrollView.contentOffset.x;
            [this drawKLine];
        }
    }];
}
-(void)dealloc
{
    [self.KVOController removeObserver:_superScrollView forKeyPath:@"contentOffset"];
}
/**
 填充视图
 */
- (void)stockFill
{
    [self initConfig];//初始化属性
    [self initLayer];//初始化图层，移除原先的，根据最新数据绘制新的
    [self.superScrollView layoutIfNeeded];
    [self calcuteCandleWidth];//计算每一个蜡烛的宽度
    [self updateWidth];//计算K线图视图和父视图的宽度及可滚动范围
    [self drawKLine];//绘制K线
}
/**
 初始化属性
 */
-(void)initConfig
{
    self.candleSpace = 3.0f;//蜡烛间的间距
    self.displayCount = 60;//当前视图展示的蜡烛个数
    self.lineWidth = 1.0f;//K线图线宽
    self.leftMargin = 2.0f;//K线图左边间距
    self.rightMargin = 2.0f;//K线图右边间距
    self.topMargin = 20.f;//K线图上边间距，蜡烛的最高点距离边框的距离
    self.bottomMargin = 0;//K线图底部间距
    self.minHeight = 1;//K线图最小起始高度
    self.kvoEnable = YES;//
    self.timeLayerHeight = 15.0f;//时间图层的高度
}

/**
 初始化图层，移除原先的，根据最新数据绘制新的
 */
- (void)initLayer
{
    if (self.lineChartLayer)
    {
        [self.lineChartLayer removeFromSuperlayer];
        self.lineChartLayer = nil;
    }
    
    if (!self.lineChartLayer)
    {
        self.lineChartLayer = [CAShapeLayer layer];
        self.lineChartLayer.strokeColor = [UIColor clearColor].CGColor;
        self.lineChartLayer.fillColor = [UIColor clearColor].CGColor;
    }
    [self.layer addSublayer:self.lineChartLayer];
    
    if (self.timeLayer)
    {
        [self.timeLayer removeFromSuperlayer];
        self.timeLayer = nil;
    }
    
    if (!self.timeLayer)
    {
        self.timeLayer = [CAShapeLayer layer];
        self.timeLayer.contentsScale = [UIScreen mainScreen].scale;
        self.timeLayer.strokeColor = [UIColor clearColor].CGColor;
        self.timeLayer.fillColor = [UIColor clearColor].CGColor;
    }
    [self.layer addSublayer:self.timeLayer];
    
    //ma5
    if (self.ma5LineLayer)
    {
        [self.ma5LineLayer removeFromSuperlayer];
    }
    
    if (!self.ma5LineLayer)
    {
        self.ma5LineLayer = [CAShapeLayer layer];
        self.ma5LineLayer.lineWidth = self.lineWidth;
        self.ma5LineLayer.lineCap = kCALineCapRound;
        self.ma5LineLayer.lineJoin = kCALineJoinRound;
    }
    [self.layer addSublayer:self.ma5LineLayer];
    
    //ma10
    if (self.ma10LineLayer)
    {
        [self.ma10LineLayer removeFromSuperlayer];
    }
    
    if (!self.ma10LineLayer)
    {
        self.ma10LineLayer = [CAShapeLayer layer];
        self.ma10LineLayer.lineWidth = self.lineWidth;
        self.ma10LineLayer.lineCap = kCALineCapRound;
        self.ma10LineLayer.lineJoin = kCALineJoinRound;
    }
    [self.layer addSublayer:self.ma10LineLayer];
    
    //ma25
    if (self.ma25LineLayer)
    {
        [self.ma25LineLayer removeFromSuperlayer];
    }
    
    if (!self.ma25LineLayer)
    {
        self.ma25LineLayer = [CAShapeLayer layer];
        self.ma25LineLayer.lineWidth = self.lineWidth;
        self.ma25LineLayer.lineCap = kCALineCapRound;
        self.ma25LineLayer.lineJoin = kCALineJoinRound;
    }
    [self.layer addSublayer:self.ma25LineLayer];
}

/**
 计算每一个蜡烛的宽度,这个宽度是动态计算的，根据父视图的宽度和当前界面要展示的个数计算
 */
- (void)calcuteCandleWidth
{
    self.candleWidth = (self.superScrollView.width - (self.displayCount - 1) * self.candleSpace - self.leftMargin - self.rightMargin) / self.displayCount;
}

/**
 计算K线图视图和父视图的宽度及可滚动范围
 */
- (void)updateWidth
{
    CGFloat klineWidth = self.dataArray.count*(self.candleWidth) + (self.dataArray.count - 1 ) *self.candleSpace + self.leftMargin + self.rightMargin;
    if(klineWidth < self.superScrollView.width)
    {
        klineWidth = self.superScrollView.width;
    }
    
    [self mas_updateConstraints:^(MASConstraintMaker *make) {
        make.width.equalTo(@(klineWidth));
    }];
    self.superScrollView.contentSize = CGSizeMake(klineWidth,0);
    [self layoutIfNeeded];
    self.superScrollView.contentOffset = CGPointMake(klineWidth - self.superScrollView.width, 0);
}

/**
 绘制K线
 */
- (void)drawKLine
{
    if (self.dataArray.count == 0) {
        return;
    }
    [self removeAllSubLayers];
    [self initCurrentDisplayModels];


    [self calcuteMaxAndMinValue];
    [self initLayer];
    [self initModelPositoin];
    [self drawCandleSublayers];
    [self drawMALayer];//绘制MA线
    [self drawTimeLayer];
    [self drawAxisLine];
    
    
    //将当前界面最左边展示位置和开始索引及展示数量传递给其他界面
    if (self.delegate && [self.delegate respondsToSelector: @selector(displayScreenleftPostion:startIndex:count:)])
    {
        [_delegate displayScreenleftPostion:self.leftPostion startIndex:self.currentStartIndex count:self.displayCount];
    }
    
    //传递当前界面的最后一个模型数据及MA线数据
    if (self.delegate && [self.delegate respondsToSelector:@selector(displayLastModel:andMALinesNUmberArray:)]) {
        //获取MA线数据
        NSMutableArray *maArray = [NSMutableArray array];
        
        StockLineData *MA5lineDatas = self.maLines[0];
        StockLineData *MA10lineDatas = self.maLines[1];
        StockLineData *MA25lineDatas = self.maLines[2];
        
        [maArray addObject:MA5lineDatas.data.lastObject];
        [maArray addObject:MA10lineDatas.data.lastObject];
        [maArray addObject:MA25lineDatas.data.lastObject];
        
        StockKLineModel *lastModel = self.currentDisplayArray.lastObject;
        [self.delegate displayLastModel:lastModel andMALinesNUmberArray:maArray];
    }
    
    
}

/**
 移除所有图层
 */
- (void)removeAllSubLayers
{
    for (NSInteger i = 0 ; i < self.lineChartLayer.sublayers.count; i++)
    {
        CAShapeLayer *layer = (CAShapeLayer*)self.lineChartLayer.sublayers[i];
        [layer removeFromSuperlayer];
        layer = nil;
    }
    
    for (NSInteger i = 0 ; i < self.timeLayer.sublayers.count; i++)
    {
        id layer = self.timeLayer.sublayers[i];
        [layer removeFromSuperlayer];
        layer = nil;
    }
}

/**
 计算最大值和最小值
 */
- (void)calcuteMaxAndMinValue
{
    self.maxY = CGFLOAT_MIN;
    self.minY  = CGFLOAT_MAX;
    NSInteger idx = 0;
    //遍历当前范围内显示的K线模型数组
    for (NSInteger i = idx; i < self.currentDisplayArray
         .count; i++)
    {
        StockKLineModel * entity = [self.currentDisplayArray objectAtIndex:i];
        self.minY = self.minY < [entity.Low floatValue] ? self.minY : [entity.Low floatValue];
        self.maxY = self.maxY > [entity.High floatValue] ? self.maxY : [entity.High floatValue];
        
        if (self.maxY - self.minY < 0.5)
        {
            self.maxY += 0.5;
            self.minY -= 0.5;
        }
    }
    //Y值缩放比例
    self.scaleY = (self.height - self.topMargin - self.bottomMargin - self.timeLayerHeight) / (self.maxY - self.minY);
}

/**
 获取显示在当前视图上的数据模型
 */
- (void)initCurrentDisplayModels
{
    NSInteger needDrawKLineCount = self.displayCount ;
    NSInteger currentStartIndex = self.currentStartIndex;
    NSInteger count = (currentStartIndex + needDrawKLineCount) >self.dataArray.count ? self.dataArray.count :currentStartIndex+needDrawKLineCount;
    [self.currentDisplayArray removeAllObjects];
    
    if (currentStartIndex < count)
    {
        for (NSInteger i = currentStartIndex; i <  count ; i++)
        {
            StockKLineModel *model = self.dataArray[i];
            [self.currentDisplayArray addObject:model];
        }
    }
}

/**
 计算当前视图上所有K线的位置
 */
- (void)initModelPositoin
{
    [self.currentPostionArray removeAllObjects];//移除旧的位置信息
    for (NSInteger i = 0 ; i < self.currentDisplayArray.count; i++)
    {
        StockKLineModel *entity  = [self.currentDisplayArray objectAtIndex:i];
        CGFloat open = ((self.maxY - [entity.Open floatValue]) * self.scaleY);
        CGFloat close = ((self.maxY - [entity.Close floatValue]) * self.scaleY);
        CGFloat high = ((self.maxY - [entity.High floatValue]) * self.scaleY);
        CGFloat low = ((self.maxY - [entity.Low floatValue]) * self.scaleY);
        CGFloat left = self.leftPostion+ ((self.candleWidth + self.candleSpace) * i) + self.leftMargin;
        
        if (left >= self.superScrollView.contentSize.width)
        {
            left = self.superScrollView.contentSize.width - self.candleWidth/2.f;
        }
        StockKLinePositionModel *positionModel = [StockKLinePositionModel initWithOpen:CGPointMake(left, open) Close:CGPointMake(left, close) High:CGPointMake(left, high) Low:CGPointMake(left,low) Date:entity.date];
        positionModel.isDrawDate = entity.isShowDay;
        [self.currentPostionArray addObject:positionModel];
    }
}

/**
 绘制K线底层图层
 */
- (void)drawCandleSublayers
{
    __weak typeof(self) this = self;
    [_currentPostionArray enumerateObjectsUsingBlock:^(StockKLinePositionModel *obj, NSUInteger idx, BOOL * _Nonnull stop) {
        CAShapeLayer *subLayer = [this getShaperLayer:obj];
        [this.lineChartLayer addSublayer:subLayer];
    }];
}
/**
 绘制MA图层
 */
- (void)drawMALayer
{
    [self calcuteMaLinePostion];
    [self drawMALineLayer];
}
/**
 计算MA线每一个点的位置
 */
- (void)calcuteMaLinePostion
{
    //清空盛放所有MA线点的数组
    [self.maPostionArray removeAllObjects];
    [self.maLines removeAllObjects];
//    NSMutableArray *maLines = [[NSMutableArray alloc] init];
    //将当前显示的模型数组，颠倒一下元素顺序
    NSMutableArray *array = (NSMutableArray*)[[self.currentDisplayArray reverseObjectEnumerator] allObjects];
    [self.maLines addObject:computeMAData(array,5)];
    [self.maLines addObject:computeMAData(array,10)];
    [self.maLines addObject:computeMAData(array,25)];

    for (NSInteger i = 0;i<self.maLines.count;i++)
    {
        StockLineData *lineData = [self.maLines objectAtIndex:i];
        NSMutableArray *array = [NSMutableArray array];
        for (NSInteger j = 0;j <lineData.data.count; j++)
        {
            StockKLineUntil *until = lineData.data[j];
            
            CGFloat xPosition = self.leftPostion + ((self.candleWidth  + self.candleSpace) * j) + self.candleWidth/2;
            CGFloat yPosition = ((self.maxY - until.value) *self.scaleY) + self.topMargin;
            StockLinePointModel *model = [StockLinePointModel  initPositon:xPosition yPosition:yPosition color:lineData.color];
            [array addObject:model];
        }
        [self.maPostionArray addObject:array];
    }
    
    
}

/**
 绘制MA线
 */
- (void)drawMALineLayer
{
    NSMutableArray *pathsArray = [UIBezierPath drawLines:self.maPostionArray];
    
    StockLinePointModel *ma5Model = self.maPostionArray[0][0];
    StockLinePointModel *ma10Model = self.maPostionArray[1][0];
    StockLinePointModel *ma25Model = self.maPostionArray[2][0];
    
    UIBezierPath *ma5Path = pathsArray[0];
    self.ma5LineLayer.path = ma5Path.CGPath;
    self.ma5LineLayer.strokeColor = ma5Model.lineColor.CGColor;
    self.ma5LineLayer.fillColor = [[UIColor clearColor] CGColor];
    self.ma5LineLayer.contentsScale = [UIScreen mainScreen].scale;
    
    UIBezierPath *ma10Path = pathsArray[1];
    self.ma10LineLayer.path = ma10Path.CGPath;
    self.ma10LineLayer.strokeColor = ma10Model.lineColor.CGColor;
    self.ma10LineLayer.fillColor = [[UIColor clearColor] CGColor];
    self.ma10LineLayer.contentsScale = [UIScreen mainScreen].scale;
    
    UIBezierPath *ma25Path = pathsArray[2];
    self.ma25LineLayer.path = ma25Path.CGPath;
    self.ma25LineLayer.strokeColor = ma25Model.lineColor.CGColor;
    self.ma25LineLayer.fillColor = [[UIColor clearColor] CGColor];
    self.ma25LineLayer.contentsScale = [UIScreen mainScreen].scale;

}

/**
 绘制时间图层
 */
- (void)drawTimeLayer
{
    [self.currentPostionArray enumerateObjectsUsingBlock:^(StockKLinePositionModel *model, NSUInteger idx, BOOL * _Nonnull stop) {
        if (model.isDrawDate)
        {
            //时间
            CATextLayer *layer = [self getTextLayer];
            layer.string = model.date;
            if (isEqualZero(model.highPoint.x))
            {
                layer.frame =  CGRectMake(0, self.height - self.timeLayerHeight - self.bottomMargin, 60, self.timeLayerHeight);
            }
            
            else
            {
                layer.position = CGPointMake(model.highPoint.x + self.candleWidth, self.height - self.timeLayerHeight/2 - self.bottomMargin);
                layer.bounds = CGRectMake(0, 0, 70, self.timeLayerHeight);
            }
            [self.timeLayer addSublayer:layer];
            
            //时间线,纵线
            CAShapeLayer *lineLayer = [self getAxispLayer];
            if (idx == self.currentPostionArray.count - 1) {
                lineLayer.strokeColor = [UIColor clearColor].CGColor;
            }
            UIBezierPath *path = [UIBezierPath bezierPath];
            path.lineWidth = 0.5f;
            lineLayer.lineWidth = 0.5f;
            
            [path moveToPoint:CGPointMake(model.highPoint.x + self.candleWidth/2 - self.lineWidth/2, 1)];
            [path addLineToPoint:CGPointMake(model.highPoint.x + self.candleWidth/2 - self.lineWidth/2 ,self.height - self.timeLayerHeight - self.bottomMargin)];
            lineLayer.path = path.CGPath;
            [self.timeLayer addSublayer:lineLayer];
        }
    }];
}

/**
 绘制当前视图的两条横线，中间和时间
 */
- (void)drawAxisLine
{
    //边框底线
    CGFloat klineWidth = (self.dataArray.count)*self.candleWidth+self.candleSpace*(self.dataArray.count);
    CAShapeLayer *bottomLayer = [self getAxispLayer];
    bottomLayer.lineWidth = 0.5f;
    UIBezierPath *bpath = [UIBezierPath bezierPath];
    [bpath moveToPoint:CGPointMake(0, self.height - self.timeLayerHeight - self.bottomMargin)];
    [bpath addLineToPoint:CGPointMake(self.width, self.height - self.timeLayerHeight - self.bottomMargin)];
    bottomLayer.path = bpath.CGPath;
    [self.timeLayer addSublayer:bottomLayer];
    
    //中间横线
    CAShapeLayer *centXLayer = [self getAxispLayer];
    UIBezierPath *xPath = [UIBezierPath bezierPath];
    [xPath moveToPoint:CGPointMake(0,self.centerY)];
    [xPath addLineToPoint:CGPointMake(klineWidth,self.centerY)];
    centXLayer.path = xPath.CGPath;
    centXLayer.lineWidth = 0.5f;
    [self.timeLayer addSublayer:centXLayer];
}
/**
监听属性
 */
- (void)setKvoEnable:(BOOL)kvoEnable
{
    _kvoEnable = kvoEnable;
}
/**
 计算K线最左边的起始位置
 
 @return 返回值
 */
- (NSInteger)leftPostion
{
    CGFloat scrollViewOffsetX = _contentOffset <  0  ?  0 : _contentOffset;
    if (_contentOffset + self.superScrollView.width >= self.superScrollView.contentSize.width)
    {
        scrollViewOffsetX = self.superScrollView.contentSize.width - self.superScrollView.width;
    }
    return scrollViewOffsetX;
}

/**
 获取开始绘制的索引
 @return 索引
 */
- (NSInteger)currentStartIndex
{
    CGFloat scrollViewOffsetX = self.leftPostion < 0 ? 0 : self.leftPostion;
    NSInteger leftArrCount = ABS(scrollViewOffsetX) / (self.candleWidth+self.candleSpace);
    if (self.dataArray.count == 0) {
        return 0;
    }else{
        if (leftArrCount > self.dataArray.count)
        {
            _currentStartIndex = self.dataArray.count - 1;
        }
        
        else if (leftArrCount == 0)
        {
            _currentStartIndex = 0;
        }
        
        else
        {
            _currentStartIndex =  leftArrCount ;
        }
        return _currentStartIndex;
    }

}


/**
 绘制每一个小蜡烛
 @param postion 位置坐标
 @return 返回图层
 */
- (CAShapeLayer*)getShaperLayer:(StockKLinePositionModel*)postion
{
    CGFloat openPrice = postion.openPoint.y + self.topMargin;
    CGFloat closePrice = postion.closePoint.y + self.topMargin;
    CGFloat hightPrice = postion.highPoint.y + self.topMargin;
    CGFloat lowPrice = postion.lowPoint.y + self.topMargin;
    CGFloat x = postion.openPoint.x;
    CGFloat y = openPrice > closePrice ? (closePrice) : (openPrice);
    CGFloat height = MAX(fabs(closePrice-openPrice), self.minHeight);
    
    CGRect rect = CGRectMake(x, y, self.candleWidth, height);
    UIBezierPath *path = [UIBezierPath drawKLine:openPrice close:closePrice high:hightPrice low:lowPrice candleWidth:self.candleWidth rect:rect xPostion:x lineWidth:self.lineWidth];
    
    CAShapeLayer *subLayer = [CAShapeLayer layer];
    if (postion.openPoint.y >= postion.closePoint.y)
    {
        subLayer.strokeColor = [UIColor Stock_PriceUpColor].CGColor;
        subLayer.fillColor = [UIColor Stock_PriceUpColor].CGColor;
    }
    else
    {
        subLayer.strokeColor = [UIColor Stock_PriceDownColor].CGColor;
        subLayer.fillColor = [UIColor Stock_PriceDownColor].CGColor;
    }
    
    subLayer.path = path.CGPath;
    [path removeAllPoints];
    return subLayer;
}

/**
 获取文本图层
 @return 图层
 */
- (CATextLayer*)getTextLayer
{
    CATextLayer *layer = [CATextLayer layer];
    layer.contentsScale = [UIScreen mainScreen].scale;
    layer.fontSize = font12ScreenWRate * LKScreenW;
    layer.alignmentMode = kCAAlignmentCenter;
    layer.foregroundColor =
    [UIColor Stock_TextColor].CGColor;
    return layer;
}

- (CAShapeLayer*)getAxispLayer
{
    CAShapeLayer *layer = [CAShapeLayer layer];
    layer.strokeColor = [UIColor Stock_BoxColor].CGColor;
    layer.fillColor = [[UIColor clearColor] CGColor];
    layer.contentsScale = [UIScreen mainScreen].scale;
    return layer;
}

- (void)reload
{
    if (self.dataArray.count == 0)
    {
        [self mas_updateConstraints:^(MASConstraintMaker *make) {
            make.width.equalTo(@(self.superScrollView.width));
        }];
        
        self.superScrollView.contentSize = CGSizeMake(self.superScrollView.width,0);
        return;
    }
    
    CGFloat prevContentOffset = self.superScrollView.contentSize.width;
    CGFloat klineWidth = self.dataArray.count*(self.candleWidth) + (self.dataArray.count - 1) *self.candleSpace + self.leftMargin + self.rightMargin;
    if(klineWidth < self.superScrollView.width)
    {
        klineWidth = self.superScrollView.width;
    }
    
    [self mas_updateConstraints:^(MASConstraintMaker *make) {
        make.width.equalTo(@(klineWidth));
    }];
    
    self.superScrollView.contentSize = CGSizeMake(klineWidth,0);
    self.superScrollView.contentOffset = CGPointMake(klineWidth - prevContentOffset,0);
    [self layoutIfNeeded];
    [self drawKLine];
}

/**
 长按手势返回对应model的相对位置
 
 @param xPostion 手指在屏幕的位置
 @return 距离手指位置最近的model位置
 */
-(CGPoint)getLongPressModelPostionWithXPostion:(CGFloat)xPostion
{
    CGFloat localPostion = xPostion;
    NSInteger startIndex = (NSInteger)((localPostion - self.leftPostion) / (self.candleSpace + self.candleWidth));
    NSInteger arrCount = self.currentPostionArray.count;
    for (NSInteger index = startIndex > 0 ? startIndex - 1 : 0; index < arrCount; ++index) {
        StockKLinePositionModel *kLinePositionModel = self.currentPostionArray[index];
        
        CGFloat minX = kLinePositionModel.highPoint.x - (self.candleSpace + self.candleWidth/2);
        CGFloat maxX = kLinePositionModel.highPoint.x + (self.candleSpace + self.candleWidth/2);
        
        if(localPostion > minX && localPostion < maxX)
        {
            if (self.delegate && [self.delegate respondsToSelector:@selector(longPressCandleViewWithIndex:kLineModel:andMALinesNUmberArray:)]) {
                
                //获取MA线数据
                NSMutableArray *maArray = [NSMutableArray array];
                StockLineData *MA5lineDatas = self.maLines[0];
                StockLineData *MA10lineDatas = self.maLines[1];
                StockLineData *MA25lineDatas = self.maLines[2];
                [maArray addObject:MA5lineDatas.data[index]];
                [maArray addObject:MA10lineDatas.data[index]];
                [maArray addObject:MA25lineDatas.data[index]];
                
                [self.delegate longPressCandleViewWithIndex:index kLineModel:self.currentDisplayArray[index] andMALinesNUmberArray:maArray];
                
            }
            
            return CGPointMake(kLinePositionModel.highPoint.x, kLinePositionModel.openPoint.y);
        }
    }
    
    //最后一根线
    StockKLinePositionModel *lastPositionModel = self.currentPostionArray.lastObject;
    
    if (localPostion >= lastPositionModel.closePoint.x)
    {
        return CGPointMake(lastPositionModel.highPoint.x, lastPositionModel.openPoint.y);
    }
    
    //第一根线
    StockKLinePositionModel *firstPositionModel = self.currentPostionArray.firstObject;
    if (firstPositionModel.closePoint.x >= localPostion)
    {
        return CGPointMake(firstPositionModel.highPoint.x, firstPositionModel.openPoint.y);
    }
    
    return CGPointZero;
}

#pragma mark panGestureRecognizerAction
- (void)panGestureRecognizer:(UIPanGestureRecognizer*)panGestureRecognizer
{
    switch (panGestureRecognizer.state)
    {
        case UIGestureRecognizerStateBegan:
        {
            
        }break;
            
        case UIGestureRecognizerStateChanged:
        {
            
        }break;
            
        case UIGestureRecognizerStateEnded:
        {
            //给定一个临界初始值(负数)
            if (self.superScrollView.contentOffset.x <= -10)
            {
                if (self.delegate && [self.delegate respondsToSelector:@selector(displayMoreDataWithLastDataModel:)])
                {
                    //记录上一次的偏移量
                    self.previousOffsetX = _superScrollView.contentSize.width  -_superScrollView.contentOffset.x;
                    StockKLineModel *model = self.dataArray.firstObject;
                    
                    [_delegate displayMoreDataWithLastDataModel:model];
                }
            }
        }break;
        default:
            break;
    }
}


@end
